﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using FXSStation.Modules.SharedInfrastructureModule.BusinessClasses.Chart;

namespace FXSStation.Modules.SharedInfrastructureModule.BusinessClasses.Chart_Indicators
{
    public class WeightedMovingAverage : IndicatorBase
    {
        int counter;
        public WeightedMovingAverage(int perdid, ObservableCollection<StockItem> data)
            : base(perdid, data)
        {
            this._chartData.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_chartData_CollectionChanged);
        }
        void _chartData_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Reset)
            {
                counter = 0;
                this.IndicatorData.Clear();
            }
                
            CalculateDynamic();
        }

        public override void Calculate()
        {
            this.IndicatorData.Clear();
            for (int i = 0; i < this._chartData.Count; i++)
            {
                double value = 0;
                int weight = this.Period;
                int weightDelimiter = 0;
                if (i > this.Period)
                {
                    for (int j = i - this.Period; j < i; j++)
                    {
                        value += this._chartData[j].Close * weight;
                        weightDelimiter += weight;
                        weight--;
                    }
                    this.IndicatorData.Add(value / weightDelimiter);
                }
                else
                {
                    this.IndicatorData.Add(null);
                }
            }
        }

        public override void CalculateDynamic()
        {
            if (counter < Period)
            {
                this.IndicatorData.Add(null);
            }
            else
            {
                double value = 0;
                int weight = this.Period;
                int weightDelimiter = 0;

                for (int j = counter - Period; j < counter; j++)
                {
                    value += this._chartData[j].Close * weight;
                    weightDelimiter += weight;
                    weight--;
                }
                this.IndicatorData.Add(value / weightDelimiter);
            }
            counter++;
        }
    }
}
